package com.blyat.xsoft.admin.restful.service.impl;

import com.blyat.xsoft.admin.restful.entity.Authority;
import com.blyat.xsoft.admin.restful.mapper.AuthorityMapper;
import com.blyat.xsoft.admin.restful.service.AuthorityService;
import com.blyat.xsoft.kernel.restful.pagination.PageList;
import com.blyat.xsoft.kernel.restful.service.CrudService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: syh
 * @Date: 2020/8/26
 * @Description:
 */
@Service
public class AuthorityServiceImpl extends CrudService<Authority, AuthorityMapper> implements AuthorityService {
    @Override
    public List<Authority> getAuthorityTree(String query) {
        List<Authority> menuList = mapper.getByParams(Collections.singletonMap("query", query));
        if (menuList != null && !menuList.isEmpty()) {
            Map<String, List<Authority>> menuMap = menuList.stream().collect(Collectors.groupingBy(Authority::getPid));
            Set<String> ids = new HashSet<>();
            List<Authority> tree = createMenuTree(Authority.ROOT, ids, menuMap);
            List<String> noRootNodes = menuMap.keySet().stream().filter(m -> !ids.contains(m)).collect(Collectors.toList());
            noRootNodes.forEach(pid -> {
                if (menuMap.containsKey(pid)) {
                    tree.addAll(menuMap.get(pid));
                }
            });
            return tree;

        }
        return new ArrayList<>();
    }

    private List<Authority> createMenuTree(String pid, Set<String> ids, Map<String, List<Authority>> map) {
        return Optional.ofNullable(map.get(pid)).orElseGet(() -> new ArrayList<>()).stream()
                .filter(m -> pid.equals(m.getPid()))
                .sorted(Comparator.comparing(Authority::getSort))
                .map(x -> {
                    Authority.Meta meta = new Authority.Meta();
                    meta.setTitle(x.getName());
                    meta.setIcon(x.getIcon());
                    meta.setNoCache(x.isNoCache());
                    x.setMeta(meta);
                    x.setChildren(createMenuTree(x.getId(), ids, map));
                    if (ids != null) ids.add(pid);
                    return x;
                }).collect(Collectors.toList());
    }
}
